<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单创建修复测试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .test-section { margin: 20px 0; padding: 15px; border: 1px solid #ccc; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        .test-btn { padding: 8px 12px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; margin: 5px; }
        .test-btn:hover { background: #0056b3; }
        .json-display { background: #f8f9fa; padding: 10px; border-radius: 4px; white-space: pre-wrap; font-family: monospace; font-size: 12px; max-height: 200px; overflow-y: auto; }
    </style>
</head>
<body>
    <h1>订单创建修复测试</h1>
    
    <div class="test-section">
        <h3>修复说明</h3>
        <div class="info">
            <strong>问题原因：</strong>checkout.js中的createOrder方法只是模拟API调用，没有真正调用后端API<br>
            <strong>修复内容：</strong>将模拟API调用改为真实的后端API调用<br>
            <strong>修复文件：</strong>js/checkout.js
        </div>
    </div>
    
    <div class="test-section">
        <h3>1. 模拟用户登录</h3>
        <button class="test-btn" onclick="simulateLogin()">模拟用户登录</button>
        <div id="loginResult"></div>
    </div>
    
    <div class="test-section">
        <h3>2. 测试修复后的订单创建</h3>
        <button class="test-btn" onclick="testFixedOrderCreation()">测试订单创建</button>
        <div id="orderCreationResult"></div>
    </div>
    
    <div class="test-section">
        <h3>3. 验证订单保存</h3>
        <button class="test-btn" onclick="verifyOrderSaved()">验证订单保存</button>
        <div id="verificationResult"></div>
    </div>
    
    <div class="test-section">
        <h3>4. 检查订单文件</h3>
        <button class="test-btn" onclick="checkOrderFile()">检查订单文件</button>
        <div id="orderFileResult"></div>
    </div>
    
    <div class="test-section">
        <h3>5. 调试信息</h3>
        <div id="debugInfo"></div>
    </div>

    <!-- 引入必要的脚本 -->
    <script src="js/api.js"></script>
    <script src="js/auth.js"></script>
    
    <script>
        // 重写console.log来显示在页面上
        const originalLog = console.log;
        const originalWarn = console.warn;
        const originalError = console.error;
        
        function addToConsole(message, type = 'info') {
            const debugDiv = document.getElementById('debugInfo');
            const timestamp = new Date().toLocaleTimeString();
            debugDiv.innerHTML += `<div class="${type}">[${timestamp}] ${message}</div>`;
            debugDiv.scrollTop = debugDiv.scrollHeight;
        }
        
        console.log = function(...args) {
            originalLog.apply(console, args);
            addToConsole(args.join(' '), 'info');
        };
        
        console.warn = function(...args) {
            originalWarn.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        console.error = function(...args) {
            originalError.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        let testOrderNumber = null;
        
        // 模拟用户登录
        function simulateLogin() {
            const resultDiv = document.getElementById('loginResult');
            try {
                const userData = {
                    username: 'Mike',
                    user_id: 'USER001',
                    email: 'mike@example.com',
                    phone: '1234567890',
                    user_type: 'Customer',
                    token: 'test-token-mike'
                };
                
                localStorage.setItem('currentUser', JSON.stringify(userData));
                localStorage.setItem('userData', JSON.stringify(userData));
                localStorage.setItem('authToken', userData.token);
                
                if (window.authManager) {
                    window.authManager.currentUser = userData;
                    window.authManager.isLoggedIn = true;
                    window.authManager.userType = userData.user_type;
                }
                
                resultDiv.innerHTML = '<div class="success">✓ 用户登录成功</div>';
                console.log('用户登录成功:', userData);
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ 登录失败: ' + error.message + '</div>';
                console.error('登录失败:', error);
            }
        }
        
        // 测试修复后的订单创建
        async function testFixedOrderCreation() {
            const resultDiv = document.getElementById('orderCreationResult');
            try {
                console.log('开始测试修复后的订单创建...');
                
                // 模拟checkout.js中的订单数据格式
                const orderData = {
                    items: [
                        {
                            productId: 'F006',
                            product_name: '修复测试商品',
                            price: 77.77,
                            quantity: 2
                        }
                    ],
                    shippingAddress: {
                        name: '修复测试用户',
                        phone: '13800138000',
                        address: '修复测试地址'
                    },
                    paymentMethod: 'alipay',
                    discount: 10
                };
                
                console.log('订单数据:', orderData);
                
                // 直接调用API（模拟checkout.js修复后的逻辑）
                const result = await window.api.createOrder(orderData);
                console.log('API调用结果:', result);
                
                if (result.success) {
                    testOrderNumber = result.data.order_number;
                    resultDiv.innerHTML = `
                        <div class="success">✓ 订单创建成功</div>
                        <div class="info">订单号: ${testOrderNumber}</div>
                        <div class="json-display">${JSON.stringify(result.data, null, 2)}</div>
                    `;
                    console.log('订单创建成功:', result.data);
                } else {
                    resultDiv.innerHTML = '<div class="error">✗ 订单创建失败: ' + result.error + '</div>';
                    console.error('订单创建失败:', result.error);
                }
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ 创建订单错误: ' + error.message + '</div>';
                console.error('创建订单错误:', error);
            }
        }
        
        // 验证订单保存
        async function verifyOrderSaved() {
            const resultDiv = document.getElementById('verificationResult');
            try {
                console.log('开始验证订单保存...');
                
                const result = await window.api.getOrders();
                console.log('获取订单列表结果:', result);
                
                if (result.success) {
                    const orders = result.data.orders || [];
                    const hasTestOrder = testOrderNumber ? orders.some(order => order.order_number === testOrderNumber) : false;
                    
                    resultDiv.innerHTML = `
                        <div class="success">✓ 订单验证完成</div>
                        <div class="info">总订单数: ${orders.length}</div>
                        <div class="info">测试订单存在: ${hasTestOrder ? '是' : '否'}</div>
                        ${hasTestOrder ? `<div class="success">✓ 修复成功！订单已正确保存</div>` : '<div class="error">✗ 订单未找到，可能仍有问题</div>'}
                    `;
                    console.log('订单验证完成，总订单数:', orders.length);
                } else {
                    resultDiv.innerHTML = '<div class="error">✗ 获取订单失败: ' + result.error + '</div>';
                    console.error('获取订单失败:', result.error);
                }
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ 验证订单错误: ' + error.message + '</div>';
                console.error('验证订单错误:', error);
            }
        }
        
        // 检查订单文件
        async function checkOrderFile() {
            const resultDiv = document.getElementById('orderFileResult');
            try {
                console.log('检查订单文件...');
                
                const result = await window.api.getOrders();
                
                if (result.success) {
                    resultDiv.innerHTML = `
                        <div class="success">✓ 订单文件检查成功</div>
                        <div class="info">当前用户订单数量: ${result.data.orders.length}</div>
                        <div class="json-display">${JSON.stringify(result.data.orders, null, 2)}</div>
                    `;
                    console.log('订单文件检查完成，订单数量:', result.data.orders.length);
                } else {
                    resultDiv.innerHTML = '<div class="error">✗ 获取订单文件失败: ' + result.error + '</div>';
                    console.error('获取订单文件失败:', result.error);
                }
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ 检查订单文件错误: ' + error.message + '</div>';
                console.error('检查订单文件错误:', error);
            }
        }
        
        // 页面加载完成后运行
        window.addEventListener('load', () => {
            console.log('订单创建修复测试页面加载完成');
        });
    </script>
</body>
</html>
